#!/usr/bin/python

#   iDebMaker
# A free program for creating .deb packages for Cydia on the iPhone/iTouch
# By Stephen Eisenhauer (BHSPitMonkey) <mail@stepheneisenhauer.com>
# Version 0.1a
#
# This code is released under the New BSD License.  Please don't claim my work
# as your own, as this is widely regarded as an uncool thing to do.

import os.path
import sys
import subprocess
import string

# Check for the presence of dpkg
try:
	subprocess.Popen(["dpkg-deb"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
except OSError:
	print >>sys.stderr, "dpkg-deb was not found on this system. Please ensure that it is properly installed."
	sys.exit(1)




print "\n\tiDebMaker - Let's make a .deb package for Cydia.\n"

# Give the user five chances to tell us a valid path to the data. Oh, he will talk.
for i in range(1,6):
	print "Please enter the path to your app's directory."
	print "This directory should be a root-level set of files to be added to the phone."
	appdir = raw_input()
	if os.path.exists(appdir):
		break
	else:
		print "The location specified does not exist.  Try again. (" + str(6-i) + ")"
if not os.path.exists(appdir):
	print >>sys.stderr, "I've heard enough invalid locations from you. Exiting."
	sys.exit(2)
else:
	appdir = os.path.abspath(appdir)
print "\nUsing app directory:\t" + appdir
print "dpkg-deb" + " -b " + appdir


# Check for the presence of a DEBIAN subdir there, and make it if need be
if not os.path.exists(appdir + "/DEBIAN"):
	os.makedirs(appdir + "/DEBIAN")
# Check for the presence of a control file, and confirm its overrision
if os.path.exists(appdir + "/DEBIAN/control"):
	print "\nWARNING: control file already exists for this app. " \
	+ "To continue, overwriting this file, type YES."
	if string.upper(raw_input("(CTRL+C to cancel and exit):\t")) == "YES":
		print "\nContinuing anyway."
	else:
		sys.exit()


# User-input values
print "\nPlease fill out the following fields, and be careful - " \
+ "I won't tell you if your value isn't valid (as of today)!\n"

identifier = raw_input("Identifier:\t\t") # TODO: check for sanity
title = raw_input("Package Name:\t\t")
version = raw_input("Version:\t\t")
section = raw_input("Category:\t\t")	# drop-down list with custom
maintainer = raw_input("Maintainer (You):\t")
author = raw_input("Author:\t\t\t")
homepage = raw_input("More Info URL:\t\t") #TODO: check for sanity
shortdescription = raw_input("Short Description:\t")
longdescription = raw_input("Long Description:\t")

print "\nNow, enter related packages (if any) separated by ', '.\n"
depends = raw_input("Dependencies:\t")
conflicts = raw_input("Conflicting Packages:\t")

print "\nIf this is a 1.x (Legacy) app, say something (anything) now."
firmware2 = raw_input("(If not, just hit Return.)\t")
if len(firmware2) != 0 and not firmware2.isspace():		# If they typed something
	print "1.x it is."
	architecture = "darwin-arm"
else:
	print "2.x it is."
	architecture = "iphoneos-arm"


# Prepare a string representing the control file.
controlcontents = \
"Package: " + identifier + \
"\nName: " + title + \
"\nVersion: " + version + \
"\nArchitecture:" + architecture + \
"\nDescription: " + shortdescription + \
"\n " + longdescription + \
"\nHomepage: " + homepage + \
"\nMaintainer: " + maintainer + \
"\nAuthor: " + author + \
"\nSection: " + section + \
"\nDepends: " + depends + \
"\nConflicts: " + conflicts + "\n\n"

# "\nInstalled-Size: " + str(installed_size) # Not sure if this one's necessary


# Open a file called control and write it
controlfile = open(appdir + "/DEBIAN/control", 'w')
controlfile.write(controlcontents)
controlfile.close()
print "\nControl file created."

# Finally, make the deb.
print "\nOkay, now let's try and actually create the package:\n"
try:
    retcode = subprocess.call(['dpkg-deb', '-b', appdir])
    if retcode < 0:
        print >>sys.stderr, "dpkg was terminated by signal", -retcode
    elif retcode == 0:
    	print "\nSuccess!  Your .deb package was created!\n"
    else:
        print >>sys.stderr, "dpkg returned code", retcode
except OSError, e:
    print >>sys.stderr, "This sucks! Execution failed:", e
